package com.uchengwang.ui.cm_ui.umsg.ui;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.uchengwang.R;
import com.uchengwang.functions.db.manager.WantCHatDBManage;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ui.BaseWithTitleActivity;
import com.uchengwang.ui.cm_ui.rychat.fragment.ConversationFragmentEx;
import com.uchengwang.ui.cm_ui.rychat.ui.ChatPersonSettingActivity;
import com.uchengwang.ui.cm_ui.rychat.widget.LoadingDialog;
import com.uchengwang.ui.cm_ui.umsg.bean.WantChatBean;
import com.uchengwang.ui.cm_ui.umsg.http.ChatHttpManager;
import com.uchengwang.ui.utils.SPUtils;

import java.util.Collection;
import java.util.Iterator;

import de.greenrobot.event.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.MessageTag;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.TypingMessage.TypingStatus;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * Created by U城网 on 2017/12/18.
 */

public class WantChatActivity extends BaseWithTitleActivity implements View.OnClickListener{
    /**
     * 对方id
     */
    private String mTargetId;
    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;
    /**
     * title
     */
    private String nickName;
    /**
     * 是否在讨论组内，如果不在讨论组内，则进入不到讨论组设置页面
     */
    private boolean isFromPush = false;

    private LoadingDialog mDialog;

    private final String TextTypingTitle = "对方正在输入...";
    private final String VoiceTypingTitle = "对方正在讲话...";

    private Handler mHandler;

    public static final int SET_TEXT_TYPING_TITLE = 1;
    public static final int SET_VOICE_TYPING_TITLE = 2;
    public static final int SET_TARGET_ID_TITLE = 0;
    private WantChatBean bean;

    @Override
    @TargetApi(23)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation);
        mDialog = new LoadingDialog(this);
        UChengApplication.chatType = 1;


        initData();
    }

    private void initData(){
        Intent intent = getIntent();

        bean = (WantChatBean) getIntent().getSerializableExtra(BaseConfig.BEAN);
        mConversationType = (Conversation.ConversationType) intent.getSerializableExtra(BaseConfig.TYPE);
        mTargetId = String.valueOf(bean.getUid());
        nickName = bean.getChatName();

        setActionBarTitle(mConversationType, mTargetId);

        setRightImage(90, R.drawable.chat_setting_image, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                enterSettingActivity();
            }
        });


        isPushMessage(intent);

        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case SET_TEXT_TYPING_TITLE:
                        setTitle(TextTypingTitle);
                        break;
                    case SET_VOICE_TYPING_TITLE:
                        setTitle(VoiceTypingTitle);
                        break;
                    case SET_TARGET_ID_TITLE:
                        setActionBarTitle(mConversationType, mTargetId);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        RongIMClient.setTypingStatusListener(new RongIMClient.TypingStatusListener() {
            @Override
            public void onTypingStatusChanged(Conversation.ConversationType type, String targetId, Collection<TypingStatus> typingStatusSet) {
                //当输入状态的会话类型和targetID与当前会话一致时，才需要显示
                if (type.equals(mConversationType) && targetId.equals(mTargetId)) {
                    int count = typingStatusSet.size();
                    //count表示当前会话中正在输入的用户数量，目前只支持单聊，所以判断大于0就可以给予显示了
                    if (count > 0) {
                        Iterator iterator = typingStatusSet.iterator();
                        TypingStatus status = (TypingStatus) iterator.next();
                        String objectName = status.getTypingContentType();

                        MessageTag textTag = TextMessage.class.getAnnotation(MessageTag.class);
                        MessageTag voiceTag = VoiceMessage.class.getAnnotation(MessageTag.class);
                        //匹配对方正在输入的是文本消息还是语音消息
                        if (objectName.equals(textTag.value())) {
                            mHandler.sendEmptyMessage(SET_TEXT_TYPING_TITLE);
                        } else if (objectName.equals(voiceTag.value())) {
                            mHandler.sendEmptyMessage(SET_VOICE_TYPING_TITLE);
                        }
                    } else {//当前会话没有用户正在输入，标题栏仍显示原来标题
                        mHandler.sendEmptyMessage(SET_TARGET_ID_TITLE);
                    }
                }
            }
        });

        /**
         * 向服务器提交一个聊天记录
         * */
        ChatHttpManager.getManager().createChat(this, 1, Long.parseLong(mTargetId), null);

        //返回数值 0代表存在 并且时间没超过规定数值  1代表存在 但是时间超过10分钟 会更新数据库 发送信息 2表示不存在 会插入进数据库 发送信息
        int isSend = WantCHatDBManage.getManage().isSend(this, bean);
        switch (isSend){
            case 1:
            case 2:
                sendMsg();
                break;
        }

    }

    private void sendMsg(){
        //发送一个小灰条信息
        ChatHttpManager.getManager().sendMsg(this, "ta通过享聊给你发来信息", mTargetId, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                if (stutas ==0 && bean != null && !bean.isChat()){
                    //小灰条发送成功后, 并且第一次聊 发送我的个人聊天宣言过去
//                    RongChatManager.getUtils().sendTextMsg(WantFindPersonsActivity.chatSign, mTargetId, Conversation.ConversationType.PRIVATE);
//                    bean.setChat(true);
                    EventBus.getDefault().post(bean);
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        initData();
    }

    /**
     * 判断是否是 Push 消息，判断是否需要做 connect 操作
     */
    private void isPushMessage(Intent intent) {
        if (intent == null)
            return;
        enterFragment(mConversationType, mTargetId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (RongIM.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.DISCONNECTED){
            enterActivity();
        }
    }

    private void enterActivity() {
        String token = SPUtils.getPreferences(this).getRyToken();
        reconnect(token);
    }

    private void reconnect(String token) {
        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
            }

            @Override
            public void onSuccess(String s) {
                if (mDialog != null)
                    mDialog.dismiss();
                enterFragment(mConversationType, mTargetId);
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                if (mDialog != null)
                    mDialog.dismiss();
                enterFragment(mConversationType, mTargetId);
            }
        });

    }

    private ConversationFragmentEx fragment;

    /**
     * 加载会话页面 ConversationFragmentEx 继承自 ConversationFragment
     *
     * @param mConversationType 会话类型
     * @param mTargetId         会话 Id
     */
    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {
        fragment = new ConversationFragmentEx();

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();

        fragment.setUri(uri);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //xxx 为你要加载的 id
        transaction.add(R.id.rong_content, fragment);
        transaction.commitAllowingStateLoss();
    }


    /**
     * 设置会话页面 Title
     *
     * @param conversationType 会话类型
     * @param targetId         目标 Id
     */
    private void setActionBarTitle(Conversation.ConversationType conversationType, String targetId) {
        if (conversationType == null)
            return;
        if (conversationType.equals(Conversation.ConversationType.PRIVATE)) {
            setPrivateActionBar(targetId);
        } else {
            setTitle(R.string.de_actionbar_sub_defult);
        }
    }

    /**
     * 设置私聊界面 ActionBar
     */
    private void setPrivateActionBar(String targetId) {
        if (!TextUtils.isEmpty(nickName)) {
            if (TextUtils.isEmpty(nickName)) {
                if (!TextUtils.isEmpty(targetId)) {
                    UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(targetId);
                    if (userInfo != null) {
                        setTitle(userInfo.getName());
                    }
                }
            } else {
                setTitle(nickName);
            }
        } else {
            setTitle(targetId);
        }
    }

    /**
     * 根据 targetid 和 ConversationType 进入到设置页面
     */
    private void enterSettingActivity() {
        Intent intent = new Intent(this, ChatPersonSettingActivity.class);
        intent.putExtra(BaseConfig.UID, Long.parseLong(mTargetId));
        intent.putExtra(BaseConfig.USER_AVATAR, "");
        intent.putExtra(BaseConfig.NICK_NAME, nickName);

        if (intent != null) {
            startActivityForResult(intent, 500);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 501) {
        }
    }

    @Override
    protected void onDestroy() {
        RongIMClient.setTypingStatusListener(null);
        UChengApplication.chatType = 0;
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            if (fragment != null && !fragment.onBackPressed()) {
                if (isFromPush) {
                    isFromPush = false;
                    this.finish();
                } else {
                    if (fragment.isLocationSharing()) {
                        fragment.showQuitLocationSharingDialog(this);
                        return true;
                    }
                    this.finish();
                }
            }
        }
        return false;
    }


    @Override
    public void onClick(View v) {
        enterSettingActivity();
    }
}
